package com.ruibang.glass.portal.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.DictInfo;
import com.ruibang.glass.portal.constant.Constants;
import com.ruibang.glass.portal.constant.UserErrorCode;
import com.ruibang.glass.portal.domain.DeptBase;
import com.ruibang.glass.portal.domain.Tree;
import com.ruibang.glass.portal.domain.UserPageParams;
import com.ruibang.glass.portal.entity.DeptEntity;
import com.ruibang.glass.portal.entity.UserEntity;
import com.ruibang.glass.portal.mapper.DeptMapper;
import com.ruibang.glass.portal.mapper.UserMapper;
import com.ruibang.glass.portal.util.BuildTree;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class DeptService extends ServiceImpl<DeptMapper, DeptEntity> implements IService<DeptEntity> {
    @Autowired
    @Lazy
    private UserMapper userMapper;
    @Autowired
    @Lazy
    private UserService userService;

    @Autowired
    private RedisSingleService redisService;

//    @Autowired
//    private RedisSingleService redisService;


    /**
     * 获取部门结构树
     *
     * @return
     */
    public ResultBody<Tree<DeptEntity>> getTree(DeptEntity dept) {
        List<Tree<DeptEntity>> trees = new ArrayList();
        DeptEntity deptEntity = new DeptEntity();
        deptEntity.setDeptName(dept.getDeptName());
        List<DeptEntity> deptList = baseMapper.getDeptList(deptEntity);

        Optional.ofNullable(deptList).ifPresent(a -> {
            a.forEach(d -> {
                Tree<DeptEntity> tree = new Tree();
                tree.setId(d.getDeptId());
                tree.setParentId(d.getParentDeptId());
                tree.setText(d.getDeptName());
                tree.setCode(d.getDeptCode());
                tree.setDisabled(d.getStatus().equals(1) ? false : true);
                tree.setFactory(Constants.ONE_STR.equals(d.getDeptType()) ? true : false);
                trees.add(tree);
            });
        });


        Tree<DeptEntity> t = BuildTree.build(trees);

        String userId = userService.getUserId();
        if (StringUtils.isNotBlank(userId)) {
            UserEntity entity = userMapper.getUserById(userId);
            if (entity != null) {
                return ResultBody.success(getDept(t));
            }
        }

        return ResultBody.success(t);
    }


    /**
     * 获取设备部下部门信息
     *
     * @return
     */
    public ResultBody<Tree<DeptEntity>> getEquipmentDept() {
        List<Tree<DeptEntity>> trees = new ArrayList();
        DeptEntity deptEntity = new DeptEntity();
        deptEntity.setDeptName("设备部");
        List<DeptEntity> deptList = baseMapper.getEquipmentDept();

        Optional.ofNullable(deptList).ifPresent(a -> {
            a.forEach(d -> {
                Tree<DeptEntity> tree = new Tree();
                tree.setId(d.getDeptId());
                tree.setParentId(d.getParentDeptId());
                tree.setText(d.getDeptName());
                tree.setCode(d.getDeptCode());
                tree.setDisabled(d.getStatus().equals(1) ? false : true);
                tree.setFactory(Constants.ONE_STR.equals(d.getDeptType()) ? true : false);
                trees.add(tree);
            });
        });


        Tree<DeptEntity> t = BuildTree.build(trees);

        return ResultBody.success(t);
    }



    /***
     * 获取部门以及下级部门
     * @param deptTree
     * @return
     */
    public Tree<DeptEntity> getDept(Tree<DeptEntity> deptTree) {
        if (CollectionUtils.isNotEmpty(deptTree.getChildren())) {
            if (deptTree.getChildren().get(0) != null) {
                Tree<DeptEntity> tree = deptTree.getChildren().get(0);
                if (CollectionUtils.isNotEmpty(tree.getChildren())) {
                    for (Tree<DeptEntity> child : tree.getChildren()) {
                        if (child == null) continue;
                        List<Tree<DeptEntity>> nodes = new ArrayList<>();
                        nodes.add(child);
                        Tree<DeptEntity> root = new Tree();
                        root.setId("-1");
                        root.setParentId("");
                        root.setHasParent(false);
                        root.setChildren(true);
                        root.setChecked(true);
                        root.setChildren(nodes);
                        root.setText("顶级节点");
                        Map<String, Object> state = new HashMap();
                        state.put("opened", true);
                        root.setState(state);
                        return root;
                    }
                }
            }
        }
        return deptTree;
    }


    public ResultBody<DeptEntity> getDeptInfoByUserID(String userId) {

        if (!Optional.ofNullable(userId).isPresent()) {
            return ResultBody.fail(UserErrorCode.PARAM_ERROR.getCode(), UserErrorCode.PARAM_ERROR.getMsg());
        }

        UserEntity entity = userMapper.getUserById(userId);

        if (!Optional.ofNullable(entity).isPresent()) {
            return ResultBody.fail(UserErrorCode.NOT_EXISTS.getCode(), UserErrorCode.NOT_EXISTS.getMsg());
        }

        return ResultBody.success(Optional.ofNullable(getDept(entity.getDeptId())).orElse(new DeptEntity()));
    }

    /**
     * 根据部门信息获取部门id
     *
     * @param deptId
     * @return
     */
    public DeptEntity getDept(String deptId) {
        return baseMapper.getDept(deptId);
    }


    /***
     * 所属工厂Id
     * @param deptId
     * @return
     */
    public String getFactory(String deptId) {
        List<DeptBase> deptBases = baseMapper.getParentByDeptId(deptId);
        if (CollectionUtils.isNotEmpty(deptBases)) {
            for (DeptBase deptBase : deptBases)
                if (Constants.ONE_STR.equals(deptBase.getDeptType())) {
                    return deptBase.getDeptId();
                }
        }

        for (DeptBase deptBase : deptBases) {
            if (Constants.ZERO_STR.equals(deptBase.getDeptType())) {
                return deptBase.getDeptId();
            }
        }

        return "";
    }


    /**
     * 保存部门信息
     */
    public ResultBody<Void> saveDept(DeptEntity deptEntity) {
        if (StringUtils.isBlank(deptEntity.getParentDeptId())
                || Constants.ZERO_STR.equals(deptEntity.getParentDeptId())) {
            deptEntity.setParentDeptId(Constants.ZERO_STR);
            deptEntity.setDeptType(Constants.ZERO_STR);
        } else {
            deptEntity.setDeptType(Constants.ONE_STR);
        }
        DeptEntity deptEt = new DeptEntity();
        deptEt.setParentDeptId(deptEntity.getParentDeptId());
        List<DeptEntity> deptEntities = baseMapper.getDeptList(deptEt);
        if (deptEntity.getCreateTime() == null) deptEntity.setCreateTime(LocalDateTime.now());
        if (deptEntity.getUpdateTime() == null) deptEntity.setUpdateTime(LocalDateTime.now());
        deptEntity.setOrderNum(Optional.ofNullable(deptEntities).isPresent() ? deptEntities.size() + 1 : 1);
        deptEntity.setStatus(Optional.ofNullable(deptEntity.getStatus()).isPresent() ? deptEntity.getStatus() : 1);
        this.save(deptEntity);
        //放入缓存
        redisService.hset(RedisKey.DEPT_GROUP_TYPE, deptEntity.getDeptId(), deptEntity.getDeptName());
        return ResultBody.success();
    }

    /**
     * @Description: 修改部门
     * @version v1.0
     * @author songJinKang
     * @date 2024-01-22 10:38
     */
    public void updateDept(DeptEntity dept) {
        log.info("开始更新部门信息：{}", JSON.toJSONString(dept));
        dept.setUpdateTime(LocalDateTime.now());
        this.updateById(dept);
        //放入缓存
        redisService.hset(RedisKey.DEPT_GROUP_TYPE, dept.getDeptId(), dept.getDeptName());
    }

    /**
     * @param deptId
     * @return
     */
    public ResultBody deleteDeptById(String deptId) {
        UserPageParams params = new UserPageParams();
        params.setDeptId(deptId);
        List<UserEntity> users = userMapper.getUserList(null, params);

        if (Optional.ofNullable(users).isPresent() && users.size() > 0) {
            return ResultBody.fail(UserErrorCode.NOT_DELET_ERROR.getCode(), UserErrorCode.NOT_DELET_ERROR.getMsg());
        }
        DeptEntity dept = new DeptEntity();
        dept.setParentDeptId(deptId);
        List<DeptEntity> deptEntities = baseMapper.getDeptList(dept);

        if (Optional.ofNullable(deptEntities).isPresent() && deptEntities.size() > 0) {
            return ResultBody.fail(UserErrorCode.NOT_DELET_ERROR_DEPT.getCode(), UserErrorCode.NOT_DELET_ERROR_DEPT.getMsg());
        }

        baseMapper.deleteDeptById(deptId);

        //删除缓存
        redisService.hdel(RedisKey.DEPT_GROUP_TYPE, deptId);

        //重新初始化缓存信息
        initDeptTree();

        return ResultBody.success();
    }

    public List<Tree<DeptEntity>> initDeptTree() {
        List<DeptEntity> deptList = this.list();
        List<Tree<DeptEntity>> trees = new ArrayList();
        Optional.ofNullable(deptList).ifPresent(a -> {
            a.forEach(d -> {
                Tree<DeptEntity> tree = new Tree<DeptEntity>();
                tree.setId(d.getDeptId());
                tree.setParentId(d.getParentDeptId());
                tree.setText(d.getDeptName());
                tree.setDisabled(d.getStatus().equals(1) ? false : true);
                trees.add(tree);
            });
        });

       /* if(CollectionUtils.isNotEmpty(trees)){
            redisService.delete(Constants.REDIS_MONITOR_DEPARTMENT_INFO);
            redisService.set(Constants.REDIS_MONITOR_DEPARTMENT_INFO,JSON.toJSONString(trees));
        }*/

        return trees;
    }

    public List<DictInfo> getByDeptIds(List<String> deptIds) {
        return baseMapper.getByDeptIds(deptIds);
    }

    public List<DeptEntity> getDeptByIds(List<String> deptIds) {
        return baseMapper.getDeptByIds(deptIds);
    }

    public List<String> getUserIdsByDeptIds(List<String> deptIds) {
        return baseMapper.getUserIdsByDeptIds(deptIds);
    }

    public String getManagerByDeptId(String deptId) {
        DeptEntity deptEntity = this.getById(deptId);
        if (deptEntity != null) {
            return deptEntity.getDeptManager();
        } else {
            return "";
        }
    }


}
